package com.example.demo.service.Impl;

import com.example.demo.dao.BillNoMapper;
import com.example.demo.dao.CheckDetailMapper;
import com.example.demo.dao.CheckMapper;
import com.example.demo.entity.Check.Check;
import com.example.demo.entity.Check.CheckDetailDTO;
import com.example.demo.service.CheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class CheckImpl implements CheckService {

    @Autowired
    CheckMapper  checkMapper;
    @Autowired
    CheckDetailMapper  checkDetailMapper;
    @Autowired
    BillNoMapper billNoMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;

    // 安全分割多个对象，处理属性值中的逗号
    private static String[] splitObjects(String input) {
        List<String> result = new ArrayList<>();
        int braceCount = 0;
        int startIndex = 0;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '{') braceCount++;
            if (c == '}') braceCount--;

            if (c == ',' && braceCount == 0) {
                result.add(input.substring(startIndex, i).trim());
                startIndex = i + 1;
            }
        }

        if (startIndex < input.length()) {
            result.add(input.substring(startIndex).trim());
        }

        return result.toArray(new String[0]);
    }

    // 解析单个对象
    private static Map<String, Object> parseObject(String objStr) {
        Map<String, Object> map = new HashMap<>();

        // 去除首尾的 {}
        objStr = objStr.trim();
        if (objStr.startsWith("{")) objStr = objStr.substring(1);
        if (objStr.endsWith("}")) objStr = objStr.substring(0, objStr.length() - 1);

        // 分割键值对
        String[] pairs = objStr.split(",\\s*");

        for (String pair : pairs) {
            int equalIndex = pair.indexOf('=');
            if (equalIndex > 0) {
                String key = pair.substring(0, equalIndex).trim();
                String value = pair.substring(equalIndex + 1).trim();
                if(!value.equals("null") && !value.equals("")) {
                    System.out.println(value.charAt(0));
                }
                // 处理 null 值
                if ("null".equalsIgnoreCase(value)) {
                    map.put(key, null);
                }
                else if (key.equals("goodsCode")) {
                    map.put(key, value);
                }
                // 处理数字类型
                else if ( value.matches("\\d+")) {
                    System.out.println(value);
                    map.put(key, Integer.valueOf(value));
                } else if (value.matches("\\d+\\.\\d+")) {
                    map.put(key, Double.valueOf(value));
                }
                // 处理字符串
                else {
                    map.put(key, value);
                }
            }
        }

        return map;
    }


    @Override//添加盘点单
    public Map<String,Object> add(Map<String, Object> param) {

        Map<String,Object> result = new HashMap<>();

        final int[] finalAdd = {0};

        transactionTemplate.execute(status -> {

            try {
                //获取BillNo
                Map<String,Object> billNoParams = new HashMap<>();
                billNoParams.put("billName","盘点单");
                LocalDate currentDate = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String formattedDate = currentDate.format(formatter);
                billNoParams.put("date",formattedDate);
                billNoMapper.getBillNo(billNoParams);
                if(billNoParams.get("billNo")==null){
                    status.setRollbackOnly();
                    result.put("status","0");
                    return result;
                }
                String billNo = billNoParams.get("billNo").toString();
                System.out.println("billno"+billNo);

                //添加明细
                ArrayList<CheckDetailDTO> objects = new ArrayList<>();
                System.out.println(param.get("checkDetails"));

                String input = param.get("checkDetails").toString();
                if(input.startsWith("[") && input.endsWith("]")){
                    input=input.substring(1,input.length()-1);
                }

                String[] strings = splitObjects(input);
                int x = 1;
                for (String string : strings) {
                    System.out.println(string);
                    Map<String, Object> stringObjectMap = parseObject(string);
                    CheckDetailDTO checkDetailDTO = new CheckDetailDTO();
                    checkDetailDTO.setBillNo(billNo);
                        checkDetailDTO.setShowNo(x);
                        x++;
                    if (stringObjectMap.get("goodsCode")!=null) {
                        System.out.println(stringObjectMap.get("goodsCode"));
                        checkDetailDTO.setGoodsCode(stringObjectMap.get("goodsCode").toString());
                    }
                    if (stringObjectMap.get("recheckQty")!=null) {
                        checkDetailDTO.setRecheckQty((int)stringObjectMap.get("recheckQty"));
                    }
                    if (stringObjectMap.get("price")!=null) {
                        checkDetailDTO.setPrice((Double) stringObjectMap.get("price"));
                    }
                    if (stringObjectMap.get("recheckPrice")!=null) {
                        checkDetailDTO.setRecheckPrice((Integer)stringObjectMap.get("recheckPrice"));
                    }
                    if (stringObjectMap.get("recheckAmount")!=null) {
                        checkDetailDTO.setRecheckAmount((Integer)stringObjectMap.get("recheckAmount"));
                    }
                    if (stringObjectMap.get("checkDiffCode")!=null) {
                        checkDetailDTO.setCheckDiffCode(stringObjectMap.get("checkDiffCode").toString());
                    }
                    if (stringObjectMap.get("waLocationCode")!=null) {
                        checkDetailDTO.setWaLocationCode(stringObjectMap.get("waLocationCode").toString());
                    }
                    if (stringObjectMap.get("nowQty")!=null) {
                        checkDetailDTO.setNowQty((int)stringObjectMap.get("nowQty"));
                    }
                    if (stringObjectMap.get("remark")!=null) {
                        checkDetailDTO.setRemark(stringObjectMap.get("remark").toString());
                    }
                    System.out.println(checkDetailDTO);
                    objects.add(checkDetailDTO);
                }

                int add = checkDetailMapper.add(objects);
                System.out.println("add"+add);
                if (add!=objects.size()) {
                    status.setRollbackOnly();
                    result.put("status","0");
                    return result;
                }

                //添加盘点单头
                Map<String,Object> checkParams = new HashMap<>();
                checkParams.put("billNo",billNo);
                checkParams.put("PDdate",param.get("PDdate"));
                // 获取当前的日期和时间
                LocalDateTime now = LocalDateTime.now();

                // 定义要格式化的模式
                DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy/M/d HH:mm:ss");

                // 格式化当前时间
                String formattedTime = now.format(formatter2);
                checkParams.put("MakeDate",formattedTime);
                checkParams.put("workingAreaCode",param.get("workingAreaCode"));
                checkParams.put("userName",param.get("userName"));
                int added = checkMapper.add(checkParams);
                if (added!=1) {
                    status.setRollbackOnly();
                    result.put("status","0");
                    return result;
                }
                result.put("status","1");
                result.put("billNo",billNo);

            }catch (Exception e){
                status.setRollbackOnly();
                e.printStackTrace();
            }
            return result;
        });

        return result;
    }

    @Override
    public Map<String, String> check(Map<String, String> param) {
        Map<String, String> result = new HashMap<>();//返回结果
        Map<String, Object> checkDateParam = new HashMap<>();
        Map<String, Object> checkParams = new HashMap<>();
//        根据bill_no查找对应的盘点单头
        String billNo = param.get("billNo");//获取bill_no
        Check check = checkMapper.findByBillNo(billNo);
        if(check==null){//如果查不到盘点单头则返回
            result.put("status","0");
            result.put("content","盘点单审核出错");
            return result;
        }
        if(check.getBillStatus().equals("已审核")){//如果盘点单已审核则返回
            result.put("status","0");
            result.put("content","盘点单已审核");
            return result;
        }
        System.out.println(check);
        String date = check.getWaCheckDate();//获取盘点日期
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            Date createDate = sdf.parse(date);
            checkDateParam.put("in_out_date",createDate);
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new IllegalArgumentException("日期格式错误",e);
        }

//        调用存储过程检查会计日期
        checkMapper.checkAccountDate(checkDateParam);
        String finish = (String) checkDateParam.get("finish");
        if(!finish.equals("n")){
            result.put("status","0");
            result.put("content","不在会计期间内");
            return result;
        }

        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义要格式化的模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d HH:mm:ss");
        // 格式化当前时间
        String checkTime = now.format(formatter);

//        进行审核
        checkParams.put("bill_no",billNo);
        checkParams.put("g_user_id",param.get("userID"));
        checkParams.put("g_user_name",param.get("userName"));
        checkMapper.check(checkParams);
        Integer ok = (Integer)checkParams.get("ok");
        if (ok==null || ok!=1) {
            result.put("status","0");
            result.put("content","审核失败");
            return result;
        }
        result.put("status","1");
        result.put("content","审核成功");
        return result;
    }

    @Override
    public Map<String, Object> find(Map<String, String> param) {
        Map<String, Object> result = new HashMap<>();
        Check check = checkMapper.findByBillNo(param.get("billNo"));
        if(check==null){
            result.put("status","0");
            result.put("content","");
            return result;
        }
        result.put("status","1");
        result.put("content",check);
        return result;
    }
}
